package encaps.action;

import encaps.entities.Grant;
import encaps.entities.Person;
import encaps.entities.PersonLocal;
import encaps.entities.PersonLocalHome;
import encaps.logging.JMSUtil;
import encaps.logging.Log;
import encaps.resources.Labels;
import encaps.utils.*;
import java.util.Date;
import javax.ejb.FinderException;
import javax.naming.NamingException;
import org.jdom.Element;

public class EditPersonAction extends Action {

    public static final String EDIT_PERSON = "editPerson";
    protected ActionContext actionContext;
    private Long id;

    public EditPersonAction(ActionContext context, Grant requiredGrant) {
        this.actionContext = context;
        this.requiredGrant = requiredGrant;
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            PersonLocalHome personHome = EntityUtil.getPersonHome();
            id = new Long(actionContext.getTextParameter(ID));
            PersonLocal person = personHome.findByPrimaryKey(id);

            JMSUtil.sendLogMessage(Log.UPDATE,
                    EntityUtil.getUserHome().findByLogin(actionContext.getUserLogin()).getID(),
                    actionContext.getUserLogin(), new Date(), Person.TABLE_NAME,
                    id, person.getName());

            Element personElement = XMLHelper.toXMLElement(person, Labels.getLabel(Labels.EDIT_PERSON), true, actionContext);
            return personElement;
        } catch (NamingException ex) {
            throw new ActionExecutionException("Cannot find PesronLocalHome object", ex);
        } catch (FinderException ex) {
            throw new ActionExecutionException("Person " + id + " not found", ex);
        } catch (SystemException ex) {
            throw new ActionExecutionException("System malfunction", ex);
        }
    }
}
